package JZOffer;

import java.util.*;

// https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/?envType=study-plan&id=lcof&plan=lcof&plan_progress=xxj1ozje
// 从上到下打印二叉树III
public class Day006_3 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        boolean flg = false;
        List<List<Integer>> list = new LinkedList<>();
        if (root == null) {
            return list;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int sz = queue.size();
            List<Integer> list1 = new LinkedList<>();
            Deque<Integer> stack = new ArrayDeque<>();
            if (!flg) {
                while (sz > 0) {
                    TreeNode node = queue.poll();
                    list1.add(node.val);
                    if (node.left != null) {
                        queue.offer(node.left);
                    }
                    if (node.right != null) {
                        queue.offer(node.right);
                    }
                    sz--;
                }
            } else {
                while (sz > 0) {
                    TreeNode node = queue.poll();
                    stack.push(node.val);
                    if (node.left != null) {
                        queue.offer(node.left);
                    }
                    if (node.right != null) {
                        queue.offer(node.right);
                    }
                    sz--;
                }
                while (!stack.isEmpty()) {
                    list1.add(stack.poll());
                }
            }
            list.add(list1);
            flg = !flg;
        }
        return list;
    }
}
